package org.light.utils;

import java.security.MessageDigest;
import java.util.List;

public class PasswordUtil {
	public static String sha1(String val) throws Exception {
		MessageDigest md = MessageDigest.getInstance("SHA1");
		md.update(val.getBytes());
		byte[] digest = md.digest();

		StringBuffer hexstr = new StringBuffer();
		String shaHex = "";
		for (int i = 0; i < digest.length; i++) {
			shaHex = Integer.toHexString(digest[i] & 0xFF);
			if (shaHex.length() < 2) {
				hexstr.append(0);
			}
			hexstr.append(shaHex);
		}
		return hexstr.toString();
	}

	public static String generateSalt(List<String> salts) throws Exception {
		String salt = "";
		char[] pinletters = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		do {
			salt = "";
			for (int i = 0; i < 8; i++) {
				salt += pinletters[(int) (Math.random() * 16)];
			}
		} while (!uniqueSalt(salt, salts));
		return salt;
	}

	public static boolean uniqueSalt(String salt, List<String> salts) throws Exception {
		if (!StringUtil.isBlank(salt)&&salts!=null) {
			if (salts.contains(salt))
				return false;
			else
				return true;
		} else if (salts == null) {
			System.out.println("The salts is empty!");
			return true;
		}
		else {
			System.out.println("The salt is empty!");
			return false;
		}
	}
	
	public static String getPassword(String plain,String salt) throws Exception{
		return sha1(sha1(sha1(plain))+salt);
	}
	
	public static void main(String [] args) throws Exception{
		System.out.println(getPassword("Mala","1f7b169c"));
		System.out.println(generateSalt(null));
	}

}
